package ar.edu.sccs.util;

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * Utilities to parse strings into XML DOM Documents and vice versa
 */
public final class XmlHelper {

	/**
	 * uses Dom4j to neatly format a given XML string by adding indents,
	 * newlines etc.
	 */
	public static String getAsPrettyXml(String xmlString) {
		return getAsPrettyXml(parse(xmlString));
	}

	/**
	 * Override that accepts an XML DOM Document
	 * 
	 * @param document
	 *            XML as DOM Document
	 */
	public static String getAsPrettyXml(Document document) {
		OutputFormat format = new OutputFormat(" ", true);
		format.setSuppressDeclaration(true);
		StringWriter out = new StringWriter();
		XMLWriter writer = new XMLWriter(out, format);
		try {
			try {
				writer.write(document);
			} finally {
				writer.close();
			}
		} catch (IOException ioe) {
			throw new RuntimeException(ioe);
		}
		return out.toString().trim();
	}

	/**
	 * Converts a String into XML by parsing into a DOM Document uses Dom4j
	 */
	public static Document parse(String xmlString) {
		try {
			return DocumentHelper.parseText(xmlString);
		} catch (DocumentException de) {
			throw new RuntimeException(de);
		}
	}

	public static Element getNewElement(String name) {
		return DocumentHelper.createElement(name);
	}

	public static Document getNewDocument(String rootElementName) {
		Document d = DocumentHelper.createDocument();
		d.addElement(rootElementName);
		return d;
	}

	public static Document transform(Document source, Document stylesheet) {
		TransformerFactory factory = TransformerFactory.newInstance();
		try {
			Transformer transformer = factory.newTransformer(new DocumentSource(stylesheet));
			DocumentResult result = new DocumentResult();
			transformer.transform(new DocumentSource(source), result);
			return result.getDocument();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
